package event;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

public class EventSystem {

    private static EventSystem eventSystem;
    private Map<String, List<ListenerInterface>> eventListMap = new Hashtable<>();

    private EventSystem() {

    }

    public static EventSystem instance() {
        if (eventSystem == null) {
            eventSystem = new EventSystem();
        }
        return eventSystem;
    }

    public void on(String eventName, ListenerInterface obj) {
        if (obj != null) {
            if (eventListMap.containsKey(eventName)) {
                List<ListenerInterface> funcList = eventListMap.get(eventName);
                funcList.add(obj);
            }
            else {
                List<ListenerInterface> funcList = new ArrayList<>();
                funcList.add(obj);
                eventListMap.put(eventName, funcList);
            }
        }
    }

    public void off(EventBase event, ListenerInterface obj) {
        if (obj != null && eventListMap.containsKey(event.getName())) {
            List<ListenerInterface> funcList = eventListMap.get(event.getName());
            for (int i = 0; i < funcList.size(); ++i) {
                if (funcList.get(i).equals(obj)) {
                    funcList.remove(obj);
                }
            }
        }
    }

    public void dispatch(EventBase event) {
        try {
            String name = event.getName();
            if (eventListMap.containsKey(name)) {
                for (int i = 0; i < eventListMap.get(name).size(); ++i) {
                    ListenerInterface obj = eventListMap.get(name).get(i);
                    obj.process(event);
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
